package com.zhongde.cloud89app.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityOptionsCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.zhongde.cloud89app.MainActivity;
import com.zhongde.cloud89app.R;
import com.zhongde.cloud89app.activity.FroundActivity;
import com.zhongde.cloud89app.activity.LoginActivity;
import com.zhongde.cloud89app.adapter.ChildUserListAdapter;
import com.zhongde.cloud89app.utils.MyPreference;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static com.zhongde.cloud89app.base.Configuration.BASE_URL;

public class PersionFragment extends Fragment {

    private Context context;
    private TextView username, userDescribe, logout;
    private RecyclerView user_list;
    private ChildUserListAdapter childUserListAdapter;
    private List<String> userpwds = new ArrayList<>();
    private MyPreference pref;
    private FloatingActionButton add_child_user;
    private CardView zzh_view;
    Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_persion, null);
        username = view.findViewById(R.id.userName);
        userDescribe = view.findViewById(R.id.userDescribe);
        user_list = view.findViewById(R.id.child_user_list);
        user_list.setLayoutManager(new LinearLayoutManager(context));
        add_child_user = view.findViewById(R.id.add_child_user);
        zzh_view = view.findViewById(R.id.zzh_view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pref = new MyPreference(context);
        if (pref.getInt("userleve") == 2) zzh_view.setVisibility(View.GONE);
        username.setText(pref.getString("userName"));
        userDescribe.setText(pref.getString("describe"));
        logout = view.findViewById(R.id.logout);
        childUserListAdapter = new ChildUserListAdapter(R.layout.child_user_item, userpwds);
        user_list.setAdapter(childUserListAdapter);
        childUserListAdapter.getData().clear();
        childUserListAdapter.setEmptyView(R.layout.empty_view);
        childUserListAdapter.notifyDataSetChanged();
        childUserListAdapter.addChildClickViewIds(R.id.delete_user);
        childUserListAdapter.setOnItemChildClickListener((adapter, view1, position) -> {
            if (view1.getId() == R.id.delete_user) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("警告");
                builder.setMessage("确实要删除" + userpwds.get(position) + "吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    //设定PositiveButton
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        initData("2", userpwds.get(position), "");
                    }
                });
                builder.setNeutralButton("取消", null);
                builder.show();
            }
        });

        add_child_user.setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("添加设备");        //设置弹出窗口的标题
            View view12 = LayoutInflater.from(context).inflate(R.layout.add_child_user_dialog, null);
            final EditText pwd = view12.findViewById(R.id.add_child_pwd);
            final EditText beizhu = view12.findViewById(R.id.add_child_beizhu);

            builder.setView(view12);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                //设定PositiveButton
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String seid = pwd.getText().toString();
                    if (seid.trim().length() == 0) {
                        Toast.makeText(context, "请输入密码", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    String spwd = beizhu.getText().toString();
                    initData("3", seid, spwd);
                }
            });
            builder.show();
        });
        logout.setOnClickListener(v -> {


            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("警告");        //设置弹出窗口的标题
            builder.setMessage("是否确定退出登录？");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                //设定PositiveButton
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    ImageView imageView = getActivity().findViewById(R.id.toolbar_logo);
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent, ActivityOptionsCompat
                            .makeSceneTransitionAnimation(getActivity(), imageView, "zhongde_image").toBundle());


                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            getActivity().finish();
                        }
                    }, 2000);
                }
            });
            builder.setNeutralButton("取消", null);
            builder.show();

        });

        initData("1", "", "");
    }

    private void initData(String type, String password, String beizhu) {

        OkHttpUtils
                .post()
                .url(BASE_URL + "AppcallingInterface_Controller/son_user_operation.do")
                .addParams("username", pref.getString("userName"))
                .addParams("password", password.split("\\(")[0])
                .addParams("description", beizhu)
                .addParams("type", type)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        userpwds.clear();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Toast.makeText(context, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                            if (type.equals("1")) {
                                JSONArray jsonArray = jsonObject.getJSONArray("data");
                                for (int i = 0; i < jsonArray.length(); i++) {

                                    String newuser = jsonArray.getJSONObject(i).getString("password");
                                    String describe = jsonArray.getJSONObject(i).getString("describe");
                                    userpwds.add(newuser + "(" + describe + ")");

                                }
                                childUserListAdapter.notifyDataSetChanged();
                            } else {
                                initData("1", "", "");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });


    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
    }
}